let sha1 = require('sha1');
const getRawBody = require('raw-body');
let Wechat = require('./wechat')
module.exports = function (opts) {
    let wechat = new Wechat(opts)
    return function* (next) {
        let token = opts.token;
        let {
            signature,
            nonce,
            echostr,
            timestamp
        } = this.query;
        let str = [token, timestamp, nonce].sort().join('');
        let sha = sha1(str);
        if (this.method === 'GET') {
            if (sha == signature) {
                this.body = echostr + '';
            } else {
                yield next
            }
        } else if (this.method == 'POST') {
            if (sha !== signature) {
                yield next
            } else {
                (async () => {
                    let data = await getRawBody(this.req, {
                        length: this.length,
                        limit: '1mb',
                        encoding: this.charset
                    });
                    console.log('data', data.toString());
                })()

            }
        }
    }
};